//
//  FileHelper.m
//  Common
//
//  Created by leo on 13-4-8.
//
//

#import "FileHelper.h"

NSString * const kArchizeFileRootKey = @"Root";

@implementation FileHelper

+ (NSString*)getDocumentDirectory
{
	NSArray* documentsDirectories = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    if (documentsDirectories.count > 0) {
		NSString *documentsDirectory = [documentsDirectories objectAtIndex:0];
		return documentsDirectory;
	}
	return nil;
}

+ (id) decodeContentFromFile:(NSString*)pFileName
{
    NSData* data = [[NSData alloc] initWithContentsOfFile:pFileName];
    if ([data length] <= 0)
    {
        return nil;
    }
    NSKeyedUnarchiver* unArchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    id content = [unArchiver decodeObjectForKey:kArchizeFileRootKey];
    [unArchiver finishDecoding];
    return content;
}

+ (BOOL) encodeContent:(id)pContent toFile:(NSString*)pFileName
{
    NSMutableData* data = [[NSMutableData alloc] init];
    NSKeyedArchiver* archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];

    [archiver encodeObject:pContent forKey:kArchizeFileRootKey];
    [archiver finishEncoding];    

    [FileHelper createFolderIfNotExistForFile:pFileName];
    return [data writeToFile:pFileName atomically:YES];
}

+ (void) createFolderIfNotExistForFile:(NSString*)pFileName
{
    NSString* fileFolder = [pFileName stringByDeletingLastPathComponent];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:fileFolder]) {
            [fileManager createDirectoryAtPath:fileFolder
                   withIntermediateDirectories:YES
                                    attributes:nil
                                         error:nil];
    }

}

+ (BOOL) isExistFile:(NSString *)pFileName
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:pFileName];
}

+ (BOOL) saveFileName:(NSString *)fName fileData:(NSData *)data toPath:(NSString *)path
{
    NSString *fPath = [path stringByAppendingPathComponent:fName];
    [FileHelper createFolderIfNotExistForFile:fPath];
    return [data writeToFile:[path stringByAppendingPathComponent:fName] atomically:YES];
}

+ (BOOL) deleteFileWitPath:(NSString *)filePath
{
    NSFileManager* fileManager = [NSFileManager defaultManager];
    return [fileManager removeItemAtPath:filePath error:nil];
}

@end
